import { useEffect, useState, useRef } from "react";
import { Input, Affix, Button } from "antd";
import Box from "../components/Box";
import axios from "axios";
import { useLocation as useLoc, useNavigate as useNav } from "react-router-dom";

const API = "http://localhost:3001";

// 定义样式对象
const st = {
    hd: { background: "rgb(54, 207, 201)", padding: 16, transition: "all 0.3s" },
    hds: { background: "rgb(54, 207, 201)", padding: "8px 16px", boxShadow: "0 2px 8px rgba(0,0,0,0.1)", transition: "all 0.3s" },
    sch: { marginTop: 8 },
    schs: { marginTop: 0 },
    nav: { display: "flex", justifyContent: "space-around", padding: 16 },
    flt: { background: "#fff", padding: "8px 16px", borderBottom: "1px solid #eee", display: "flex", alignItems: "center", gap: 8 },
    nod: { textAlign: "center", color: "#888", margin: 16 },
    emp: { textAlign: "center", margin: 32 }
};

export default function Home() {
    const [jbs, setJbs] = useState([]);
    const [mor, setMor] = useState(true);
    const [pg, setPg] = useState(1);
    const [flt, setFlt] = useState({});
    const [sft, setSft] = useState(false);
    const [stk, setStk] = useState(false);
    const lst = useRef();
    const nav = useNav();
    const loc = useLoc();

    // 只在filter变化时加载一次数据
    useEffect(() => {
        if (loc.state && loc.state.filter) {
            setFlt(loc.state.filter);
        }
        // eslint-disable-next-line
    }, [loc.state && loc.state.filter]);

    // flt变化时加载数据
    useEffect(() => {
        setPg(1);
        setJbs([]);
        setMor(true);
        ldm(1, flt);
        // eslint-disable-next-line
    }, [flt]);

    useEffect(() => {
        const scr = () => {
            const y = window.scrollY;
            const th = 120;
            if (y > th) {
                setStk(true);
                setSft(true);
            } else {
                setStk(false);
                setSft(false);
            }
            if (window.innerHeight + window.scrollY + 100 >= document.body.scrollHeight) {
                if (mor) ldm();
            }
        };
        window.addEventListener("scroll", scr);
        return () => window.removeEventListener("scroll", scr);
    }, [mor]);

    const getJbs = async (pg = 1, flt = {}) => {
        let prm = { _page: pg, _limit: 10 };
        Object.keys(flt).forEach(k => {
            if (flt[k] && !flt[k].includes("不限")) {
                prm[k] = flt[k].join(",");
            }
        });
        const res = await axios.get(`${API}/jobs`, { params: prm });
        return res.data;
    };

    const ldm = async (npg = pg, nflt = flt) => {
        const res = await getJbs(npg, nflt);
        if (res.length < 10) setMor(false);
        setJbs(prv => (npg === 1 ? res : [...prv, ...res]));
        setPg(npg + 1);
    };

    const rft = () => {
        const tgs = [];
        Object.keys(flt).forEach(k => {
            if (flt[k] && Array.isArray(flt[k])) {
                flt[k].forEach(v => {
                    if (v && !v.includes("不限")) {
                        tgs.push(
                            <span key={`${k}-${v}`} style={{
                                background: "#f0f0f0",
                                padding: "2px 8px",
                                borderRadius: 12,
                                fontSize: 12,
                                marginRight: 4
                            }}>
                                {v}
                            </span>
                        );
                    }
                });
            }
        });
        return tgs;
    };

    return (
        <div>
            {/* 头部 */}
            <Affix offsetTop={0}>
                <div style={stk ? st.hds : st.hd}>
                    <Input.Search
                        placeholder="搜索职位名称、公司"
                        style={stk ? st.schs : st.sch}
                        size={stk ? "small" : "middle"}
                    />
                    {!stk && (
                        <Button 
                            onClick={() => nav("/filter", { state: { filter: flt } })}
                            style={{ marginTop: 8 }}
                        >
                            筛选
                        </Button>
                    )}
                </div>
            </Affix>

            {/* 导航区域 */}
            <div style={st.nav}>
                <div>附近工作</div>
                <div>热门兼职</div>
                <div>高薪机会</div>
                <div>岗位专区</div>
                <div>行业图谱</div>
            </div>

            {/* 吸顶筛选栏 */}
            {sft && (
                <Affix offsetTop={stk ? 56 : 0}>
                    <div style={st.flt}>
                        <Button 
                            size="small"
                            onClick={() => nav("/filter", { state: { filter: flt } })}
                        >
                            筛选
                        </Button>
                        {rft()}
                        {Object.keys(flt).length > 0 && (
                            <Button 
                                size="small" 
                                type="text"
                                onClick={() => {
                                    setFlt({});
                                    setPg(1);
                                    setJbs([]);
                                    setMor(true);
                                    ldm(1, {});
                                }}
                            >
                                清除
                            </Button>
                        )}
                    </div>
                </Affix>
            )}

            {/* 列表区域 */}
            <div ref={lst}>
                {jbs.length > 0 ? (
                    <Box jobs={jbs} />
                ) : (
                    <div style={st.emp}>
                        <div>没有找到合适职位，刷新试试吧</div>
                        <Button onClick={() => ldm(1, flt)}>点击刷新</Button>
                    </div>
                )}
                {!mor && jbs.length > 0 && (
                    <div style={st.nod}>
                        没有更多数据了
                    </div>
                )}
            </div>
        </div>
    );
}